package com.homer.gps.track;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.w3c.dom.Document;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.google.android.gms.maps.model.LatLng;
import com.homer.gps.track.adapters.RoutesArrayAdapter;
import com.homer.gps.track.adapters.StopsArrayAdapter;
import com.homer.gps.track.helper.GMapV2Directions;
import com.homer.gps.track.helper.UsefullStaff;
import com.homer.gps.track.persist.DatabaseHelper;
import com.homer.gps.track.persist.PlaceModel;
import com.homer.gps.track.persist.PointModel;
import com.homer.gps.track.persist.Repository;
import com.homer.gps.track.persist.RouteModel;
import com.homer.gps.track.persist.StopModel;
import com.homer.gps.track.persist.StopsHasPlacesModel;
import com.homer.gps.track.service.ITrackService;
import com.homer.gps.track.service.TrackService;
import com.homer.gps.track.service.TrackService.MyBinder;
import com.homer.gps.track.template.DefaultORMSherlockActivity;
import com.j256.ormlite.android.apptools.OpenHelperManager;

public class RunningRoute extends DefaultORMSherlockActivity {
	
	public static final String TAG = "com.homer.gps.track";
	private static final int ROUTE_EDIT_SCREEN = 101;
	private static final int NEW_STOP = 102;
	
	private TextView routeStartPlace, routeStartDate, routeStartPlaceAddress;
	private ImageView routeStartPlaceTypeIcon;
	private ImageButton startStopButton;
	private ListView stopsList;
	private StopsArrayAdapter stopsListAdapter;
	private TextView elapsedTime, speed, distance;
	private int selectedRouteId = -1;
	private RouteModel selectedRoute = null;
	private StopModel startStop = null;
	private Handler updateHandler = null;
	private Runnable updateRunnable = null;
	private ServiceConnection trackServiceConnection;
	private ITrackService trackService;
	private Repository repository;
	private List<PointModel> points = new ArrayList<PointModel>();
	private GMapV2Directions md = new GMapV2Directions();
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.running_route);
		this.repository = super.getRepository(this);
		
		selectedRouteId = getIntent().getIntExtra("createdRouteId", -1);
		if (selectedRouteId != -1) {
			selectedRoute = (RouteModel) repository.getRouteForId(selectedRouteId);
		}else {
			Log.e(TAG, "Selected route wrong ID");
		}
		
		trackServiceConnection = new ServiceConnection() {

			public void onServiceDisconnected(ComponentName name) {
				Log.i(TAG, "Track service disconnected");
				trackService = null;
				startAndBindTrackService();
			}

			public void onServiceConnected(ComponentName name, IBinder service) {
				Log.i(TAG, "Net service connected");
				trackService = ((MyBinder) service).getService();
			}
		};

		startAndBindTrackService();
		
		initActivity();
	}
	
	private void initActivity() {
		getSupportActionBar().setTitle(selectedRoute.getName().toString());
		getSupportActionBar().setHomeButtonEnabled(true);
		getSupportActionBar().setDisplayHomeAsUpEnabled(true);
		getSupportActionBar().setIcon(UsefullStaff.getRouteTypeImageResource(selectedRoute.getType()));
		
		routeStartPlace = (TextView) findViewById(R.id.start_place);
		routeStartPlaceAddress = (TextView) findViewById(R.id.start_place_address);
		routeStartDate = (TextView) findViewById(R.id.route_start_date);
		routeStartPlaceTypeIcon = (ImageView) findViewById(R.id.start_place_type_icon);
		stopsList = (ListView) findViewById(R.id.stops_list);
		List<StopModel> otherStops = null;
		try {
			otherStops = repository.lookupStopsForRoute(selectedRoute, StopModel.STOP_TYPE_OTHER);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		if (otherStops != null) {
			stopsListAdapter = new StopsArrayAdapter(this, R.layout.stops_list_item, otherStops);
		}
		
		stopsList.setAdapter(stopsListAdapter);
		
		startStopButton = (ImageButton) findViewById(R.id.start_stop_button);
		elapsedTime = (TextView) findViewById(R.id.elapsed_time);
		speed = (TextView) findViewById(R.id.aver_speed);
		distance = (TextView) findViewById(R.id.distance);
		updateHandler = new Handler();
		List<StopModel> stops = null;
		try {
			stops = repository.lookupStopsForRoute(selectedRoute, StopModel.STOP_TYPE_START);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		startStop = stops.get(0);
		updateRunnable = new Runnable() {
			@Override
			public void run() {
				elapsedTime.setText(UsefullStaff.getElapsedTime(startStop.getStartDateTime()));
//				try {
//					points = repository.lookupPointsForRoute(selectedRoute);
//					if (points.size() > 0) {
//						LatLng startLatLng = new LatLng(points.get(0).getLatitude(), points.get(0).getLongitude());
//						LatLng endLatLng = new LatLng(points.get(points.size()-1).getLatitude(), points.get(points.size()-1).getLongitude());
//						Document doc = md.getDocument(startLatLng, endLatLng, GMapV2Directions.MODE_DRIVING);
//						String dist = md.getDistanceText(doc);
//						if (dist != null) {
//							distance.setText(dist);
//						}
//					}
//				} catch (SQLException e) {
//					// TODO Auto-generated catch block
//					e.printStackTrace();
//				}
				distance.setText("1m");
				SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(RunningRoute.this);
				float speedValue = preferences.getFloat("lastspeed", 0);
				speed.setText(String.valueOf(speedValue) + "m/s");
				updateHandler.post(this);
			}
		};
		updateHandler.post(updateRunnable);
		toggleStartStopButton(selectedRoute.isRunning());
		startStopButton.setOnClickListener(new OnClickListener() {

			public void onClick(View arg0) {
				Intent i = new Intent(RunningRoute.this, RouteEdit.class);
				i.putExtra("id", selectedRouteId);
				startActivityForResult(i, ROUTE_EDIT_SCREEN);
			}
		});
		
		if (startStop != null) {
			routeStartDate.setText(UsefullStaff.getFormatedDateAndTime(startStop.getStartDateTime(), "dd/MM/yyyy"));
			PlaceModel startPlace = null;
			try {
				startPlace = repository.lookupPlacesForStop(startStop);
				if (startPlace != null) {
					routeStartPlace.setText(startPlace.getName());
					routeStartPlaceAddress.setText(startPlace.getParsedAddress());
					routeStartPlaceTypeIcon.setImageResource(UsefullStaff.getPlaceTypeImageResource(startPlace.getType()));
					routeStartPlaceTypeIcon.setVisibility(View.VISIBLE);
				}
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		switch (requestCode) {
		case ROUTE_EDIT_SCREEN:
			if (resultCode == Activity.RESULT_OK) {
				trackService.toggleTracking(selectedRouteId);
				updateHandler.removeCallbacks(updateRunnable);
				selectedRoute.toggleRunning();
				repository.saveOrUpdateRoute(selectedRoute);
				toggleStartStopButton(selectedRoute.isRunning());
				Intent i = new Intent(RunningRoute.this, Routes.class);
				startActivity(i);
			}
			break;
		case NEW_STOP:
			if (resultCode == Activity.RESULT_OK) {
				int selectedItemId = data.getIntExtra("selectedItemId", -1);
				if (selectedItemId > -1) {
					PlaceModel stopPlace = repository.getPlaceForId(selectedItemId);
					final StopModel stop = new StopModel();
					stop.setStartDateTime(new Date());
					stop.setType(StopModel.STOP_TYPE_OTHER);
					stop.setRoute(selectedRoute);
					repository.saveOrUpdateStop(stop);
					repository.saveOrUpdateStopsHasPlaces(new StopsHasPlacesModel(stop, stopPlace));
					restartActivity();
				}
			}
			break;

		default:
			break;
		}
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			Intent i = new Intent(this, Routes.class);
			startActivity(i);
			return true;
		case 0:
			Intent intent = new Intent(this, MapActivity.class);
			intent.putExtra("routeId", selectedRouteId);
			startActivity(intent);
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}
	
	public void onNewStopClicked (View view) {
		Intent i = new Intent(this, Places.class);
		i.putExtra("requestCode", true);
		startActivityForResult(i, NEW_STOP);
	}
	
	public boolean onCreateOptionsMenu(Menu menu) {
        menu.add("Edit")
            .setIcon(R.drawable.place_show_on_map)
            .setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
        return true;
    }
	
	private void toggleStartStopButton(boolean trackingEnabled){
		if (trackingEnabled) {
			startStopButton.setImageResource(android.R.drawable.ic_media_pause);
		}else {
			startStopButton.setImageResource(android.R.drawable.ic_media_play);
		}
	}
	
	private void startAndBindTrackService() {
		// just for sure (if the service was killed or something)
		Intent serviceIntent = new Intent(this, TrackService.class);
		startService(serviceIntent);

		bindService(serviceIntent, trackServiceConnection, 0);
	}
	
	@Override
	public void onBackPressed() {
		super.onBackPressed();
		Intent i = new Intent(this, Routes.class);
		startActivity(i);
	}
	
	private void stopTracking(){
		
	}
	
	public void restartActivity() {

	    Intent intent = getIntent();
	    overridePendingTransition(0, 0);
	    intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
	    finish();

	    overridePendingTransition(0, 0);
	    startActivity(intent);
	}
	
}
